// ==================== 立即执行函数 ====================
$(function () {

  // ==================== 需要将请求参数对象提交到服务器 ====================
  let q = {
    sex: '',
    username: '',
    mobile: '',
    page: '',
    limit: '10',

  }

  const layer = layui.layer
  const form = layui.form

  // ==================== 渲染数据 ====================
  USER()
  async function USER() {
    const res = await axios.get('/ydd_user/list', { params: q })
    // console.log(res);
    // const count  = res.data.data.count
    if (res.data.errno !== 0) {
      return layer.msg('获取数据失败')
    }
    let num = 0
    const newData = res.data.data.data
    // console.log(newData);

    const str = newData.map((item) => {

      return `
      <tr>
        <td>${num += 1}</td>
        <td>${item.id}</td>
        <td>${item.username}</td>
        <td>${item.mobile}</td>
        <td><img src="http://124.223.14.236:8060/${item.icon}" alt="" style="width: 100px; height: 50px;" ></td>
        <td> ${item.sex = item.sex === 0 ? '男' : '女'}</td>
        <td>${item.birthday = item.birthday === null ? '' : item.birthday}</td>
        <td style="display:flex;height:50px;">
        <button type="button" class="layui-btn modification" style="margin-top:10px; " data-id='${item.id}' >编辑</button>
        <button type="button" class="layui-btn btn_delete" style="margin-top:10px; " data-id='${item.id}'>删除</button>
        </td>
      </tr>
      `
    }).join('')
    $(".box3 tbody").html(str)

    const total = res.data.data.count
    // console.log(total);

    renderPage(total)
  }

  // ==================== 分页器 ====================
  let laypage = layui.laypage;
  function renderPage(total) {
    //执行一个laypage实例
    laypage.render({
      elem: 'page-box', //注意，是 ID，不用加 # 号
      count: total,//数据总数，从服务端得到
      limit: q.limit,
      limits: [10, 20, 50, 80, 100],
      curr: q.page,
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数
        // console.log(first)
        q.page = obj.curr
        q.limit = obj.limit

        //首次不执行
        if (!first) {
          //do something
          // console.log('a');
          USER()
        }
      }
    })
  }

  // ==================== 点击新增功能 ====================
  $('.xz').click(function () {
    layer.open({
      btn: 0,
      title: '添加用户',
      area: ['700px', '350px'],
      content: `
      <form class="layui-form" action="" id="modalbox1">
      <input type="text" name="id" id="id" style="display: none">
        <div class="layui-form-item">
          <label class="layui-form-label">*用户名</label>
          <div class="layui-input-inline">
            <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input user1">
          </div>
          <label class="layui-form-label">*手机号</label>
          <div class="layui-input-inline">
            <input type="text" name="mobile" required lay-verify="required" placeholder="请输入手机号" autocomplete="off" class="layui-input mobile1">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">*密码</label>
          <div class="layui-input-inline">
            <input type="text" name="password"  placeholder="请输入密码" autocomplete="off" class="layui-input password1">
          </div>
          <div class="layui-form-item">
    <label class="layui-form-label">性别</label>
    <div class="layui-input-block">
      <input type="radio" name="sex" value="0" title="男">
      <input type="radio" name="sex" value="1" title="女" checked>
    </div>
  </div>
          <div class="layui-form-item">
            <label class="layui-form-label">用户头像</label>
            <div class="layui-input-inline">
              <input type="file" name="icon" id="change" style="display: block; margin-top:5px">
              
            </div>
          </div>
          <button class="layui-btn" lay-submit lay-filter="formDemo" id="btn" style="margin-left:550px">确定</button>
          <button class="layui-btn" lay-submit lay-filter="formDemo" id="btn">取消</button>
      </form>
      
      `
    })
    form.render()
  })
  //  ==================== 新增是动态创建的用事件委托 ====================
  $('body').on('submit', '#modalbox1', async function (e) {
    e.preventDefault();
    // 收集表单数据
    let data = $(this).serialize()
    console.log(data);
    const res = await axios.post('/ydd_user/add', data)
    console.log(res);
    if (res.data.errno === 1000) {
      return layer.msg('手机号已存在')
    }
    // 新增之后
    // 1关闭弹出层
    layer.close()
    // 2重新获取数据渲染到页面中
    USER()
    layer.msg('新增用户成功')//提示
  })

  // ==================== 点击导出下载文件 ====================
  $('.dc').click(function () {
    var table = document.getElementById("tabInfo")
    var data = []
    for (var i = 0, row; row = table.rows[i]; i++) {
      var rowData = []
      for (var j = 0, col; col = row.cells[j]; j++) {
        rowData.push(col.innerText)
      }
      data.push(rowData)
    }
    // 创建工作簿
    var workbook = XLSX.utils.book_new()

    // 创建工作表
    var worksheet = XLSX.utils.aoa_to_sheet(data)

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")

    // 导出工作簿为 Excel 文件
    XLSX.writeFile(workbook, "数据.xlsx")
  })

  //  ==================== 编辑功能 ====================
  $('body').on('click', '.modification', function () {

    layer.open({
      btn: 0,
      title: '添加用户',
      area: ['700px', '350px'],
      content: `
      <form class="layui-form" action="" id="modalbox2" lay-filter="modalbox2">
      <input type="text" name="id" id="id" style="display: none">
        <div class="layui-form-item">
          <label class="layui-form-label">*用户名</label>
          <div class="layui-input-inline">
            <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input user1">
          </div>
          <label class="layui-form-label">*手机号</label>
          <div class="layui-input-inline">
            <input type="text" name="mobile" required lay-verify="required" placeholder="请输入手机号" autocomplete="off" class="layui-input mobile1">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">*密码</label>
          <div class="layui-input-inline">
            <input type="text" name="password"  placeholder="请输入密码" autocomplete="off" class="layui-input password1">
          </div>
          <div class="layui-form-item">
    <label class="layui-form-label">性别</label>
    <div class="layui-input-block">
      <input type="radio" name="sex" value="0" title="男">
      <input type="radio" name="sex" value="1" title="女" checked>
    </div>
  </div>
          <div class="layui-form-item">
            <label class="layui-form-label">用户头像</label>
            <div class="layui-input-inline">
              <input type="file" name="icon" id="change" style="display: block; margin-top:5px">
              
            </div>
          </div>
          <button  type:"submit" class="layui-btn" lay-submit lay-filter="formDemo" id="btn" style="margin-left:550px" data-id = 1>确定</button>
          <button class="layui-btn layui-layer-close layui-layer-close1 " lay-submit lay-filter="formDemo" id="btn2" data-id = 2>取消</button>
          </form>
      `
    })
    const id = $(this).attr('data-id');
    // console.log(id);
    axios.get(`/ydd_user/rowInfo`, { params: { id } }).then((res) => {
      // 获取到数据，将其填充到表单中
      // 给表单赋值
      // editForm即class='layui-form'所在元素属性lay-filter的值可以自定义名字
      // console.log(res);
      // console.log(res.data.data);
      form.val('modalbox2', res.data.data)
    })
  })
  //  ==================== 编辑之后添加更新内容 ====================
  $('body').on('submit', '#modalbox2', async function (e) {
    e.preventDefault()
    // 收集表单数据然后提交
    let data = $(this).serialize()
    console.log(data);
    const res = await axios.post('/ydd_user/update', data)
    console.log(res);
    // 点击取消模态框隐藏
    // if ($('#btn').dataset.id !== 1) {
    //   return layer.close()
    // }


    $('body').on('click', '#btn2', function () {
      layer.closeAll()
      layer.msg('已取消')
    })

    $('body').on('click', '#btn', function () {
      // 更新之后
      // 1关闭弹出层
      layer.closeAll()
      // 2重新获取数据渲染到页面中
      USER()
      // 3提示
      layer.msg('编辑成功')
    })


  })

  // ==================== 删除功能 ====================
  $('body').on('click', '.btn_delete', function (e) {
    e.preventDefault();
    const id = $(this).attr('data-id')
    console.log(id);
    layer.confirm(
      '确认要删除吗',
      { icon: 3, title: '提示' },
      async function (index) {
        const delRes = await axios.get('/ydd_user/del?id=' + id)
        console.log(delRes);
        if (delRes.data.errno !== 0) {
          return layer.msg('默认数据不允许删除! ')
        }
        layer.msg('删除数据成功! ')
        USER()
      })
  })

  // ==================== 搜索功能 ====================
  $('#form_search .ss').on('click', function (e) {
    e.preventDefault()
    const username = $('[name=username]').val()
    console.log(username);
    const mobile = $('[name=mobile]').val()
    console.log(mobile);
    const sex1 = $('[name=template]').val()
    console.log(sex1);
    if (sex1 === '男') {
      q.sex = '0'

    } else {
      q.sex = '1'
    }
    console.log(sex1);
    q.username = username
    q.mobile = mobile
    USER()
  })

  // ==================== 重置功能 ====================
  $('#form_search .cz').on('click', function () {
    $('[name=username]').val('')
    $('[name=mobile]').val('')
    $('[name=template]').val('')
  })
































































})


